using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using UnityEditor;
using UnityEngine;

namespace Learning
{
    public class SimpleJobSystem : MonoBehaviour
    {
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.A))
            {
                NativeArray<float> result = new NativeArray<float>(100000000, Allocator.TempJob);

                SimpleJob job = new SimpleJob();
                job.result = result;
                
                var last = EditorApplication.timeSinceStartup;
                
                JobHandle handle = job.Schedule();
                handle.Complete();
                
                var now = EditorApplication.timeSinceStartup;
                var pass = now - last;
                Debug.Log("Job耗时：" + pass + "s");

                Debug.Log(result[123456]);

                result.Dispose();
            }

            if (Input.GetKeyDown(KeyCode.B))
            {
                float[] result = new float[100000000];
                
                var last = EditorApplication.timeSinceStartup;
                
                for (int i = 0; i < result.Length; i++)
                {
                    result[i] = i * Mathf.PI;
                }
                
                var now = EditorApplication.timeSinceStartup;
                var pass = now - last;
                Debug.Log("主线程耗时：" + pass + "s");
                
                Debug.Log(result[123456]);
            }
        }
    }

    [BurstCompile] // 注释和打开这里，来查看是否开启Burst编译的差异
    public struct SimpleJob : IJob
    {
        public NativeArray<float> result;
        
        public void Execute()
        {
            for (int i = 0; i < result.Length; i++)
            {
                result[i] = i * Mathf.PI;
            }
        }
    }
}
